package com.mimosa.util.config;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;

import org.apache.commons.lang3.StringUtils;

import com.mimosa.util.constant.StringConstUtil;

/**
 * 应用的配置对象
 * 
 * @date 2012-3-27
 * @filename Config.java
 * @author Yanlei Han
 */
public final class Config {
	public static final String SEX_TYPE = "sextype";
	public static final String DATABASE = "database";
	public static final String SOURCE_SITE = "sourcesite";
	public static final String DEFAULT_DATABASE = "defaultdatabase";
	public static final String FILE_TYPE = "filetype";
	public static final String LANGUAGE = "language";
	public static final String STATISTICS = "statistics";
	public static final String SORT = "sort";
	public static final String TASTTYPE = "tasktype";

	private static final Config INS = new Config();
	private Map<String, Map<String, String>> context = null;

	/**
	 * 构造函数，用于从自定义的配置中整合参数信息
	 * 
	 * @throws
	 */
	private Config() {
		// 生成对象信息
		this.context = new LinkedHashMap<String, Map<String, String>>();
		// 读取配置信息
		Properties properties = new Properties();
		Enumeration<URL> enumeration;
		try {
			enumeration = this.getClass().getClassLoader().getResources("config.xml");
			InputStream inputStream = null;
			URL url = null;
			while (enumeration.hasMoreElements()) {
				url = enumeration.nextElement();
				inputStream = url.openStream();
				try {
					properties.loadFromXML(inputStream);
					String key = null;
					String value = null;
					String[] items = null;
					for (Entry<Object, Object> entry : properties.entrySet()) {
						key = (String) entry.getKey();
						value = (String) entry.getValue();
						items = value.split(StringConstUtil.COMMA);
						Map<String, String> result = this.context.get(key);
						if (result == null) {
							result = new LinkedHashMap<String, String>();
						}

						for (String item : items) {
							if (item.contains(StringConstUtil.COLON)) {
								String[] kv = item.split(StringConstUtil.COLON);
								result.put(kv[0].toLowerCase(), kv[1]);
							} else {
								if (StringUtils.isNotBlank(item)) {
									result.put(item.toLowerCase(), item);
								}
							}
						}
						this.context.put(key, result);
					}
					properties.clear();
				} catch (IOException e) {
					throw new RuntimeException("不能读取配置文件信息", e);
				}
			}
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	}

	/**
	 * 根据配置项，返回配置项对应的KeyValue值对列表
	 * 
	 * @param itemName
	 * @return
	 */
	public static List<KeyValue> itemList(String itemName) {
		List<KeyValue> result = new ArrayList<KeyValue>();
		KeyValue keyValue = null;
		for (Entry<String, String> entry : INS.context.get(itemName).entrySet()) {
			keyValue = new KeyValue(entry.getKey(), entry.getValue());
			result.add(keyValue);
		}
		return result;
	}

	/**
	 * 获取配置中指定Key对应的Value值
	 * 
	 * @param itemName
	 *            配置项名称
	 * @param key
	 *            项配置的关键字
	 * @return
	 */
	public static String getItemValue(String itemName, String key) {
		String result = StringUtils.EMPTY;
		if (StringUtils.isNotBlank(itemName)) {
			Map<String, String> kvlist = INS.context.get(itemName.toLowerCase());
			if (StringUtils.isNotBlank(key)) {
				key=key.trim();
				result = key;
				key = key.toLowerCase();
			}
			if (kvlist != null && kvlist.containsKey(key)) {
				result = kvlist.get(key);
			}
		}
		return result;
	}

	/**
	 * 获取全部的应用环境变量配置信息
	 * 
	 * @return
	 */
	public static Map<String, Map<String, String>> getAllContextInfo() {
		return INS.context;
	}

	public static String getItemValues(String itemName, String[] keys) {
		StringBuilder builder = new StringBuilder();
		if (StringUtils.isNotBlank(itemName)) {
			Map<String, String> kvlist = INS.context.get(itemName);
			for (String key : keys) {
				if (StringUtils.isNotBlank(key)) {
					key = key.trim().toLowerCase();
				}
				if (kvlist.containsKey(key)) {
					builder.append(kvlist.get(key));
					builder.append(StringConstUtil.COMMA);
				}
			}
		}
		if (builder.length() > 1) {
			builder.deleteCharAt(builder.length() - 1);
		}
		return builder.toString();
	}

	public static String getItemValues(String itemName, String keyStr, String separator) {
		String result = StringUtils.EMPTY;
		if (StringUtils.isNotBlank(keyStr) && StringUtils.isNotBlank(separator)) {
			String[] keys = StringUtils.split(keyStr, separator);
			result = getItemValues(itemName, keys);
		}
		return result;
	}

	public static boolean containsItemKey(String itemName, String key) {
		Boolean result = Boolean.FALSE;
		if (StringUtils.isNotBlank(itemName) && StringUtils.isNotBlank(key)) {
			result = INS.context.get(itemName).containsKey(key.toLowerCase());
		}
		return result;
	}

	/**
	 * 生成JQueryUI组件Combobox认识的形式
	 * 
	 * @param itemName
	 * @return
	 */
	public static String toJsonArray(String itemName) {
		StringBuilder builder = new StringBuilder();
		Map<String, String> kvlist = INS.context.get(itemName);
		for (Entry<String, String> kv : kvlist.entrySet()) {
			builder.append("{'key':'");
			builder.append(kv.getKey()).append("','value':'");
			builder.append(kv.getValue()).append("'},");
		}
		if (builder.length() > 0)
			builder.deleteCharAt(builder.length() - 1);
		return builder.toString();
	}

	/**
	 * 根据条目的名称获取条目的全部值列表
	 * 
	 * @param itemName
	 *            条目名称
	 * @return
	 */
	public static String getAllItemKey(String itemName, String... separator) {
		Collection<String> kvlist = INS.context.get(itemName).keySet();
		String sep = StringConstUtil.COMMA;
		if (separator.length > 0)
			sep = separator[0];
		return StringUtils.join(kvlist, sep);
	}
}